package com.nipun.graph.utils;

import java.io.File;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import com.nipun.graph.objects.EdgeImpl;
import com.nipun.graph.objects.Graph;
import com.nipun.graph.objects.GraphImpl;
import com.nipun.graph.objects.Vertex;
import com.nipun.graph.objects.VertexImpl;


public class ConstructGraph {
	public static Graph getGraphFromXMLDocument(String filePath){
		Graph graph = new GraphImpl();
		Document graphDocument = XMLUtils.getDOM(new File(filePath));
		Element docElement = graphDocument.getDocumentElement();
		Object [] vertices = XMLUtils.evalXPath(docElement, "//Graph/Node", null);
		
		for(int i=0; i<vertices.length;i++){
			Node temp = (Node) vertices[i];
			if(temp.getFirstChild() != null){
				graph.addNode(new VertexImpl(temp.getFirstChild().getNodeValue()));
			}
		}
		
		Object[] edges = XMLUtils.evalXPath(docElement, "//Graph/Edge", null);
		for(int i=0; i<edges.length; i++){
			Node temp = (Node)edges[i];
			Element el = (Element)temp;
			Vertex node1 = null;
			Vertex node2 = null;
			Node firstNode = temp.getFirstChild().getNextSibling();
//			Object[] edgeData = XMLUtils.evalXPath(docElement, "/Node1", el);
			if(firstNode != null){
				String name1 = firstNode.getFirstChild().getNodeValue();
				if(graph.lookUpNode(name1) != null){
					node1 = graph.lookUpNode(name1);
				}else{
					System.out.println("edge refers to non-existant node");
					return null;
				}
			}
			Node secondNode = firstNode.getNextSibling().getNextSibling();
//			Object[] edgeData1 = XMLUtils.evalXPath(docElement, "/Node2",el);
			if(secondNode != null){
				String name2 = secondNode.getFirstChild().getNodeValue();
				if(graph.lookUpNode(name2) != null){
					node2 = graph.lookUpNode(name2);
				}else{
					System.out.println("edge refers to non-existant node");
					return null;
				}
			}
			graph.addEdge(new EdgeImpl(node1, node2));
		}
		
		return graph;
	}
}
